<template>
    <el-dialog :title="dialogTitle" v-model="visible" width="769px">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="90px">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请输入账户名称" clearable></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="onCancel" size="default">取 消</el-button>
                <el-button type="primary" @click="onSubmit(ruleFormRef)" size="default">保 存</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Menu } from '@/api/system/menu/types.ts'
import { resetForm } from '@/utils/index.ts'

const visible = ref(false)
const dialogTitle = ref('新增菜单')
const ruleFormRef = ref<FormInstance>()
/** 定义表单 */
const defaultRuleForm: Menu.Form = {
    sort: 1,
}
const ruleForm = reactive<Menu.Form>({
    sort: 1,
})
/** 定义表单校验规则 */
const rules = reactive<FormRules<Menu.Form>>({
    name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
})
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh'])

/** 关闭弹窗 */
const onCancel = () => {
    visible.value = false
}
/** 打开弹窗 */
const openDialog = (item: Menu.Form) => {
    ruleFormRef.value?.clearValidate()
    if (item) {
        dialogTitle.value = '编辑菜单'
        Object.assign(ruleForm, item)
    } else {
        dialogTitle.value = '新增菜单'
        resetForm(ruleForm, defaultRuleForm)
    }
    visible.value = true
}

const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
        }
    })
}

defineExpose({
    openDialog,
})
</script>
